var layerload;
var layercity;
//接口公共地址
var API_URL_PUBLIC = "http://localhost:8080/";
var API_URL_PUBLIC_TEST = "http://118.190.32.120:8001/api";
var isDevelop = false;


if(getCookie("at") !== ""){
    //获取cookie at字段的值，将其保存到sessionStorage 并将cookie的改字段设置为空值
    sessionStorage.setItem("token",getCookie("at"));
    setCookie("at","");
}
if(getCookie("agentId") !== ""){
    sessionStorage.setItem("agentId",getCookie("agentId"));
}
if(getCookie("agentName") !== ""){
    sessionStorage.setItem("agentName",getCookie("agentName"));
}

function $$(id) {
    return document.getElementById(id);
}

//2秒后自动关闭信息框
function msgbox(msg) {
    layer.msg(msg, {
        time: 2000
    });
}

function errbox(msg, willdo) {
    if(willdo)
        layer.alert(msg, {
            title: '出错啦',
            icon: 5, //×标志
            btn: "我知道了",
            yes: function() {
                willdo();
            },
            cancel: function() {
                willdo();
            }
        });
    else
        layer.alert(msg, {
            title: '出错啦',
            icon: 5,
            btn: "我知道了"
        });
}

function infobox(msg, willdo) {
    if(willdo)
        layer.alert(msg, {
            icon: 0,
            btn: "我知道了",
            yes: function() {
                willdo();
            },
            cancel: function() {
                willdo();
            }
        });
    else
        layer.alert(msg, {
            icon: 0,
            btn: "我知道了"
        });
}

function okbox(msg, willdo) {
    if(willdo)
        layer.alert(msg, {
            icon: 1, //打勾标志
            btn: "我知道了",
            yes: function() {
                willdo();
            },
            cancel: function() {
                willdo();
            }
        });
    else
        layer.alert(msg, {
            icon: 1,
            btn: "我知道了"
        });
}

function regionbox() {
    layercity = layer.open({
        type: 1,
        skin: 'layui-layer-rim', //加上边框
        area: ['650px', '470px'], //宽高
        title: '城市选择',
        content: regionhtml
    });

    $(document).on("click", ".selcity", function() {
        var cityId = $(this).children("span").text();
        setCookie("cityId", escape(cityId));
        setCookie("city", escape($(this).attr("title")));
        layer.close(layercity);
        window.location.reload();
    });
}

function setshowcitylist() {
    $(".divpos").on("click", function() {
        regionbox();
    });

    if(getCookie("city") == "") {
        var mapDwJs = '<script type="text/javascript" src="/js/mapDw.js"></script>';
        document.write(mapDwJs);
    }

    $(".divpos").html('<i class="ico-position"></i><a href="javascript:;" style="overflow: hidden;width: 28px;height: 18px;display: block;" class="c646">' + unescape(getCookie("city")) + "</a>");

}

function openwait() {
    layerload = layer.load();
}

function closewait() {
    if(layerload)
        delayRun("layer.close(layerload)", 150)
}

function delayRun(code, time) {
    var t = setTimeout(code, time);
}

function checkNameUseZZ(name) {
    var patten = /^((1([38]\d|4[57]|5[0-35-9]|7[06-8])\d{8})|(([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})))$/;
    if(!patten.test(name)) {
        return false;
    }
    return true;
}

function checkLogin() {
    if(getCookie("un"))
        return true;
    else
        return false;
}

function noregister() {
    //infobox("暂未开放公众注册，敬请期待，如果您是邀请测试用户，请直接登录");
    window.location.href = "/register.html";
}

function backToLogin() {
    window.location.href = "/login.html";
}

function errBackToLogin() {
    // 	var url = document.location.toString();
    // 　　var arrUrl = url.split("//");
    //
    // 　　var start = arrUrl[1].indexOf("/");
    // 　　var relUrl = arrUrl[1].substring(start);//stop省略，截取从start开始到结尾的所有字符
    // 	console.log(relUrl)
    // 	if(relUrl != "/html/sign/login.html"){
    // 		setCookie("get_phone1", "");
    // 		setCookie("good_num", "");
    // 		logout();
    // 		window.location.href = "../../html/sign/login.html";
    // 	}
}

//sessionStorage 没有token 跳转到登录页
function goLogin(){
    if(sessionStorage.getItem("token") == null || sessionStorage.getItem("token") == ""){
        parent.location.reload();
        // window.location.href = "login.html";
    }
};


function backToIndex() {
    window.location.href = "/index.html";
}

function logoRedirect() {
    $$("logo").onclick = function() {
        backToIndex();
    };
}

//导航顶部登录后返回登录前页面
function H_headLogin() {
    let Data = window.location.href;
    var domain = Data.split('//'); //以“/”进行分割
    if(domain[1]) {
        domain = domain[1];
    } else {
        domain = ''; //如果url不正确就取空
    }
    console.log(domain)
    let loginUrl = 'http://www.dianlaoban.com/api/site/redirect/2=' + domain;
    window.open(loginUrl, '_blank');
}



//退出登录
function H_headRegis() {

    $.ajax({
        url: "http://www.dianlaoban.com/api//site/loginOut",
        type: 'POST',
        dataType: "json",
        contentType: "application/x-www-form-urlencoded",
        data: {
            "unionId":getCookie("at")
        },
        success: function(data) {
            //系统错误处理段，handle那些令牌过期或者令牌非法的错误
            console.log(data)
            if(data.result == 'true'){
                setCookie("at", "");
                sessionStorage.setItem("token","")

                location.reload()
                console.log("dd")
            }
        },
        error: function(e) {
            dfd.reject(xhr);
            console.log("jj")
        }
    })
}
//退出登录
function H_headRegis2() {
    $.ajax({
        url: "http://www.dianlaoban.com/api//site/loginOut",
        type: 'POST',
        dataType: "json",
        contentType: "application/x-www-form-urlencoded",
        async: false,
        data: {
            "unionId":getCookie("at")
        },
        success: function(data) {
            //系统错误处理段，handle那些令牌过期或者令牌非法的错误
            console.log(data)
            if(data.result == 'true'){
                setCookie("at", "");
                sessionStorage.setItem("token","")

                location.reload()
            }
        },
        error: function(e) {
            dfd.reject(xhr);
        }
    })
}

function chat(to) {
    if(!checkLogin()) {
        errBackToLogin();
        return;
    }
    if((!to) || (to == 'undefine')) {
        to = 'none';
    }
    //alert("CHAT_URL:"+CHAT_URL)
    window.open(CHAT_URL + '?to=' + to);
}

//公用系统出错处理段，在其他代码之前先处理系统级别定义的错误
function doCommonError(data) {
    var tockenError = "tocken_";
    var sysError = "sys_";
    var permError = "perm_";
    if(data.result == "false") {
        closewait();
        if(data.error.code.indexOf(tockenError) >= 0) {
            //令牌错误，这个时候需要重定向到登录页面
            //backToLogin();
            errBackToLogin();
            return true;
            /*
             errbox(data.reason,function togo() {
             msgbox("这个时候要跳转登录页面了");
             return true;
             });
             */
            //window.location.href ="/index.html";
        } else if(data.error.code.indexOf(sysError) >= 0) {
            //系统错误，直接显示错误
            errbox(data.reason);
            return true;
            //window.location.href ="/index.html";
        } else if(data.error.code.indexOf(permError) >= 0) {
            //权限错误，分情况处理
            errbox(data.reason);
            return true;
            //window.location.href ="/index.html";
        }

    }
    return false;
}

function getDate() {
    return new Date().Format(DateFormatStr);
}

Date.prototype.Format = function(fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if(/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for(var k in o)
        if(new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

function encryptMD5(str) {
    return CryptoJS.MD5(str).toString(CryptoJS.enc.Hex);
}

function guid() {
    var str = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random() * 16 | 0,
            v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
    return str.replace(/-/g, "");
}

function setCookie(name, value) {
    var expdate = new Date(); //初始化时间
    expdate.setTime(expdate.getTime() + 360 * 24 * 60 * 60 * 1000); //cookie时间暂定30天
    document.cookie = name + "=" + value + ";expires=" + expdate.toGMTString() + ";path=/";
}

function getCookie(c_name) {
    if(document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=")
        if(c_start != -1) {
            c_start = c_start + c_name.length + 1
            c_end = document.cookie.indexOf(";", c_start)
            if(c_end == -1)
                c_end = document.cookie.length
            return unescape(document.cookie.substring(c_start, c_end))
        }
    }
    return ""
}

function delCookie(name) {
    var expdate = new Date(); //初始化时间
    expdate.setTime(expdate.getTime() - 1);
    var cval = getCookie(name);
    console.log(cval)
    if(cval != null)
        document.cookie = name + "=";

}

function encryptMD5(str) {
    return CryptoJS.MD5(str).toString(CryptoJS.enc.Hex);
}

/**
 * 同步ajax
 * @param data
 * @param dfd
 */
function apiService4(data, dfd) {
    var reqTime = getDate();
    $.ajax({
        url: API_URL,
        async: false,
        type: 'POST',
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({
            "funcName": data.funcName, //controller 中的方法名
            "serviceName": data.serviceName, //controller 注解名称
            "serialNumber": guid(), //请求流水
            "userAccount": data.account, //用户账户
            "reqSysCode": "A01", //请求生成端 A01-web ,A02-app, A03-微信
            "reqTime": reqTime, //请求时间
            "data": data.requestData,
            "security": data.requestSecurity //安全层
        }),
        success: function(data) {
            //系统错误处理段，handle那些令牌过期或者令牌非法的错误
            if(doCommonError(data)) {
                return;
            }
            dfd.resolve(data);
        },
        error: function(e) {
            dfd.reject(xhr);
        }
    })
}

/**
 * 异步ajax
 * @param data
 * @param dfd
 */
function apiService3(data, dfd) {
    var reqTime = getDate();
    $.ajax({
        url: API_URL,
        type: 'POST',
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({
            "funcName": data.funcName, //controller 中的方法名
            "serviceName": data.serviceName, //controller 注解名称
            "serialNumber": guid(), //请求流水
            "userAccount": data.account, //用户账户
            "reqSysCode": "A01", //请求生成端 A01-web ,A02-app, A03-微信
            "reqTime": reqTime, //请求时间
            "data": data.requestData,
            "security": data.requestSecurity //安全层
        }),
        success: function(data) {
            //系统错误处理段，handle那些令牌过期或者令牌非法的错误
            if(doCommonError(data)) {
                return;
            }
            dfd.resolve(data);
        },
        error: function(e) {
            // dfd.reject(xhr);
        }
    })
}

function apiService5( url, data_1, dfd) {
    // console.log(dfd)
    $.ajax({
        url: url,
        type: 'POST',
        dataType: "json",
        contentType: "application/x-www-form-urlencoded",
        data:data_1,
        success: function(data) {
            //系统错误处理段，handle那些令牌过期或者令牌非法的错误
            if(doCommonError(data)) {
                return;
            }
            dfd.resolve(data);
        },
        error: function(e) {
            // dfd.reject(xhr);

            console.log(e.responseJSON.reason);
            let msg = e.responseJSON.reason;
            layui.use('layer', function(){
                let layer = layui.layer;
                layer.open({
                    title:"系统提示",
                    content:'<div style="width:100%;text-align: center;">'+msg+",请扫码开通"+'</div>'+'<div style="width: 100%;"><img src="http://www.51hezuo.com.cn/img/code.png" style="display: block;margin:0 auto;"></div>' //这里content是一个普通的String
                });
            });
        }
    })
}

function apiService7( url, data_1, dfd) {
    // console.log(dfd)
    $.ajax({
        url: url,
        type: 'POST',
        dataType: "json",
        contentType: "application/x-www-form-urlencoded",
        data:data_1,
        success: function(data) {
            //系统错误处理段，handle那些令牌过期或者令牌非法的错误
            // if(doCommonError(data)) {
            //     return;
            // }
            dfd.resolve(data);
        },
        error: function(e) {
            // dfd.reject(xhr);

            // console.log(e.responseJSON.reason);
            // let msg = e.responseJSON.reason;
            //          layui.use('layer', function(){
            //              let layer = layui.layer;
            //              layer.open({
            //                  title:"系统提示",
            //                  content:'<div style="width:100%;text-align: center;">'+msg+",请扫码开通"+'</div>'+'<div style="width: 100%;"><img src="http://www.51hezuo.com.cn/img/code.png" style="display: block;margin:0 auto;"></div>' //这里content是一个普通的String
            //              });
            //          });
        }
    })
}

function apiService6( url, data_1, dfd) {
    // console.log(dfd)
    $.ajax({
        url: url,
        type: 'POST',
        dataType: "json",
        contentType: "application/x-www-form-urlencoded",
        data:data_1,
        success: function(data) {
            //系统错误处理段，handle那些令牌过期或者令牌非法的错误
            if(doCommonError(data)) {
                return;
            }
            dfd.resolve(data);
        },
        error: function(e) {
            // dfd.reject(xhr);
            // console.log(e.responseJSON.reason);

            let msg = e.responseJSON.reason;
            if(msg === "没有配置对应属性或es"){
                alert("暂无数据！")
            }

        }
    })
}

//https://segmentfault.com/q/1010000004231751
function apiService2(serviceName, funcName, requestData, dfd) {
    apiService("", "", serviceName, funcName, requestData, dfd);
}

function apiService(account, accessTocken, serviceName, funcName, requestData, dfd) {
    var reqTime = getDate();
    $.ajax({
        url: API_URL,
        type: 'POST',
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({
            "funcName": funcName, //controller 中的方法名
            "serviceName": serviceName, //controller 注解名称
            "serialNumber": guid(), //请求流水
            "userAccount": account, //用户账户
            "reqSysCode": "A01", //请求生成端 A01-web ,A02-app, A03-微信
            "reqTime": reqTime, //请求时间
            "data": requestData,
            "security": { //安全层
                //访问令牌，如果没有这个需要先访问authController中的login来获取，web端不需要手工传，在登录后后端会直接写入cookie中
                "accessTocken": accessTocken
            }
        }),
        success: function(data) {
            //系统错误处理段，handle那些令牌过期或者令牌非法的错误
            if(doCommonError(data)) {
                return;
            }
            dfd.resolve(data);
        },
        error: function(e) {
            dfd.reject(xhr);
        }
    })

}

//返回的是字符串形式的参数，例如：class_id=3&id=2&
function getUrlArgStr() {
    var q = location.search.substr(1);
    var qs = q.split('&');
    var argStr = '';
    if(qs) {
        for(var i = 0; i < qs.length; i++) {
            argStr += qs[i].substring(0, qs[i].indexOf('=')) + '=' + qs[i].substring(qs[i].indexOf('=') + 1) + '&';
        }
    }
    return argStr;
}
//返回的是对象形式的参数
function getUrlArgObject() {
    var args = new Object();
    var query = location.search.substring(1); //获取查询串
    var pairs = query.split(","); //在逗号处断开
    for(var i = 0; i < pairs.length; i++) {
        var pos = pairs[i].indexOf('='); //查找name=value
        if(pos == -1) { //如果没有找到就跳过
            continue;
        }
        var argname = pairs[i].substring(0, pos); //提取name
        var value = pairs[i].substring(pos + 1); //提取value
        args[argname] = unescape(value); //存为属性
    }
    return args; //返回对象
}

//解决ie8不支持forEach --开始
if(!Array.prototype.forEach) {

    Array.prototype.forEach = function forEach(callback, thisArg) {

        var T, k;

        if(this == null) {
            throw new TypeError("this is null or not defined");
        }
        var O = Object(this);
        var len = O.length >>> 0;
        if(typeof callback !== "function") {
            throw new TypeError(callback + " is not a function");
        }
        if(arguments.length > 1) {
            T = thisArg;
        }
        k = 0;

        while(k < len) {

            var kValue;
            if(k in O) {

                kValue = O[k];
                callback.call(T, kValue, k, O);
            }
            k++;
        }
    };
}
//解决ie8不支持forEach --结束

//获取html传参方法
function getParameterStr(str) {
    var LocString = decodeURI(window.location.href);
    var rs = new RegExp("(^|)" + str + "=([^&]*)(&|$)", "gi").exec(LocString),
        tmp;
    if(tmp = rs) {
        return tmp[2];
    }
    // parameter cannot be found
    return "";
}

//获取html传参方法
function getParameterStr2(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if(r != null) return unescape(r[2]);
    return null;
}

/**
 * 获取URL参数
 */
(function($) {
    $.getUrlParam = function(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if(r != null) return unescape(r[2]);
        return null;
    }
})(jQuery);

//获取百度地图key
function getMapKey() {
    //openwait();
    var serviceName = "dataDictController";
    var funcName = "getDataDict";
    var requestDataJson = {
        "typeGroupCode": "gVariable"
    };
    var requestSecurityJson = {};
    var data = {
        "account": "",
        "serviceName": serviceName,
        "funcName": funcName,
        "requestData": requestDataJson,
        "requestSecurity": requestSecurityJson
    };
    var ajaxDfd = $.Deferred();
    apiService4(data, ajaxDfd);
    $.when(ajaxDfd).then(function(data) {
        var httpMapKey;
        var httpsMapKey;
        $.each(data.data, function(n, value) {
            var typeCode = value.typeCode;
            var typeName = value.typeName;
            if(typeCode == 'gVariable_002')
                httpsMapKey = typeName;
            else if(typeCode == 'gVariable_003')
                httpMapKey = typeName;
        });

        if(typeof(httpsMapKey) == "undefined" && typeof(httpMapKey) == "undefined") {
            errbox("未查询到地图key,部分功能不能使用")
        }

        var mapJS;
        var ishttps = 'https:' == document.location.protocol ? true : false;
        if(ishttps) {
            mapJS = '<script type="text/javascript" src=' + httpsMapKey + '></script>';
        } else {
            mapJS = '<script type="text/javascript" src=' + httpMapKey + '></script>';
        }
        document.write(mapJS);

        //closewait();
    }, function(xhr) {
        alert("网络出错啦");
    });
}

//本地存储
function addData(name, data) {
    window.localStorage[name] = data;
}

function readData(name) {
    return window.localStorage[name];
}

function deleteData(name) {
    window.localStorage.removeItem(name);
}
//session本地存储
function addData2(name, data) {
    sessionStorage.setItem(name,data);
}

function readData2(name) {
    return sessionStorage.getItem(name);
}

function deleteData2(name) {
    sessionStorage.removeItem(name);
}

var get_phone;

function login(account, pass, imageCode, willdo) {
    openwait();
    var data = {
        "funcName": "login", //名称
        "serviceName": "authController", //服务器名称
        "requestSecurity": {
            "codeKey": readData("pass_codeKey"),
            "smsCode": imageCode
        }, //请求安全
        "requestData": { //请求数据
            "loginName": account //数据
        }
    };
    var ajaxDfd = $.Deferred();
    apiService3(data, ajaxDfd);
    $.when(ajaxDfd).then(function(data) { //这里的参数为什么是data,因为在下面的ajax函数中,我把data当成resolve()的参数传过来了
        // closewait();
        if(data.result == "true") {
            if(willdo) {
                willdo();
            }
            // get_phone = data.data.userAccount; //导航欢迎样式
            // setCookie("get_phone1", get_phone)
            // $(".headShoppingCart1").text(" 欢迎您，" + get_phone)
            // $(".headShoppingCart1").show()
        } else {
            errbox(data.reason);
        }

    }, function(xhr) { //这里的参数为什么是xhr,因为在下面的ajax函数中,我把xhr当成reject()的参数传过来了
        closewait();
        errbox(JSON.stringify(e));
    });
}
function login2(account, pass, imageCode, willdo) {
    openwait();
    let data = {
        "funcName": "siteLogin", //名称
        "serviceName": "connectController", //服务器名称
        "requestSecurity": {
            "codeKey": readData("pass_codeKey"),
            "smsCode": imageCode
        }, //请求安全
        "requestData": { //请求数据
            "loginName": account //数据
        }
    };
    let ajaxDfd = $.Deferred();
    apiService3(data, ajaxDfd);
    $.when(ajaxDfd).then(function(data) { //这里的参数为什么是data,因为在下面的ajax函数中,我把data当成resolve()的参数传过来了
        // H_cotice_infoh2(data.data)
        // closewait();
        if(data.result == "true") {
            addData2("token", data.data.token);
            // setCookie("at", data.data.token);
            setCookie("at","");
            addData2("agentId", data.data.agentId);
            addData2("agentName", data.data.agentName);
            if(willdo) {
                willdo();
            }
            // get_phone = data.data.userAccount; //导航欢迎样式
            // setCookie("get_phone1", get_phone)

            // sessionStorage.setItem("token",data.data.token);
            // console.log(readData("pass_codeKey"))
        } else {
            errbox(data.reason);
        }

    }, function(xhr) { //这里的参数为什么是xhr,因为在下面的ajax函数中,我把xhr当成reject()的参数传过来了
        closewait();
        errbox(JSON.stringify(e));
    });
}
function login_mobile(account, pass, imageCode, willdo) {
//	openwait();
    var data = {
        "funcName": "login", //名称
        "serviceName": "authController", //服务器名称
        "requestSecurity": {
            "codeKey": readData("pass_codeKey"),
            "smsCode": imageCode
        }, //请求安全
        "requestData": { //请求数据
            "loginName": account //数据
        }
    };
    var ajaxDfd = $.Deferred();
    apiService3(data, ajaxDfd);
    $.when(ajaxDfd).then(function(data) { //这里的参数为什么是data,因为在下面的ajax函数中,我把data当成resolve()的参数传过来了
        // H_cotice_infoh2(data.data)
        // closewait();
        if(data.result == "true") {
            if(willdo) {
                willdo();
            }
            // get_phone = data.data.userAccount; //导航欢迎样式
            // setCookie("get_phone1", get_phone)
            // $(".headShoppingCart1").text(" 欢迎您，" + get_phone)
            // $(".headShoppingCart1").show()
        } else {
            errbox(data.reason);
        }

    }, function(xhr) { //这里的参数为什么是xhr,因为在下面的ajax函数中,我把xhr当成reject()的参数传过来了
        closewait();
        errbox(JSON.stringify(e));
    });
}


//浏览器收藏
function addFavorite2() {
    var url = window.location;
    var title = document.title;
    var ua = navigator.userAgent.toLowerCase();
    console.log(ua)
    if(ua.indexOf("360se") > -1) {
        alert("由于360浏览器功能限制，请按 Ctrl+D 手动收藏！");
    } else if(ua.indexOf("msie 8") > -1) {
        window.external.AddToFavoritesBar(url, title); //IE8
    } else if(document.all) {
        try {
            window.external.addFavorite(url, title);
        } catch(e) {
            alert('您的浏览器不支持,请按 Ctrl+D 手动收藏!');
        }
    } else if(window.sidebar) {
        window.sidebar.addPanel(title, url, "");
    } else {
        alert('您的浏览器不支持,请按 Ctrl+D 手动收藏!');
    }
}
//检测是否登录